package com.example.myproject.redis.redisother.fangan;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * Created by xi on 2019/3/2.
 */
//@Component
public class RedisSubListenerConfig {

    //初始化监听器
    @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
            MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //container.setTopicSerializer();
        container.addMessageListener(listenerAdapter, new PatternTopic("mytopic"));
        return container;
    }

    private RedisSerializer getRedisSerializer(){
        ObjectMapper objectMapper = new ObjectMapper();
        //忽略传入到对象的多余字段的解析
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //解析的时候自动映射成类型
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        //objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        RedisSerializer serializer = new GenericJackson2JsonRedisSerializer(objectMapper);
        return serializer;
    }


    //利用反射来创建监听到消息之后的执行方法
    @Bean
    MessageListenerAdapter listenerAdapter(RedisReceiver redisReceiver) {
        MessageListenerAdapter adapter =  new MessageListenerAdapter(redisReceiver, "receiveMessage");
        adapter.setSerializer(getRedisSerializer());
        return adapter;
    }

}
